package com.zhiche.lisa.lspm.service.otm.impl;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.utils.XmlUtil;
import com.zhiche.lisa.lspm.dao.mapper.otm.OtmLisaCarrierMapper;
import com.zhiche.lisa.lspm.dao.model.otm.OtmLisaCarrier;
import com.zhiche.lisa.lspm.service.otm.IOtmLisaCarrierService;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

/**
 * <p>
 * 运力推送OTM接口日志表 服务实现类
 * </p>
 *
 * @author qichao
 * @since 2018-07-06
 */
@Service
public class OtmLisaCarrierServiceImpl extends ServiceImpl<OtmLisaCarrierMapper, OtmLisaCarrier> implements IOtmLisaCarrierService {

    private static final Logger LOGGER = LoggerFactory.getLogger(IOtmLisaCarrierService.class);

    @Override
    public Boolean insertOtmLisa(Long lspId, Long driverId, Long carrierId, Long trailerId, String otmApiUrl, String requestId) {
        Boolean blnRtn = false;
        OtmLisaCarrier otmLisaCarrier = null;

        try{
            EntityWrapper<OtmLisaCarrier> entityWrapper = new EntityWrapper<>();
            entityWrapper.eq("request_id",requestId);
            otmLisaCarrier = this.selectOne(entityWrapper);
            if(Objects.isNull(otmLisaCarrier)){
                otmLisaCarrier = new OtmLisaCarrier();
            }
        }
        catch (Exception ex){
            throw new BaseException(ex.getMessage());
        }

        // 承运商 id
        if (Objects.nonNull(lspId)) {
            otmLisaCarrier.setLspId(lspId);
        }

        // 司机 id
        if (Objects.nonNull(driverId)) {
            otmLisaCarrier.setDriverId(driverId);
        }

        // 牵引车 id
        if (Objects.nonNull(carrierId)) {
            otmLisaCarrier.setCarrierId(carrierId);
        }

        // 挂车 id
        if (Objects.nonNull(trailerId)) {
            otmLisaCarrier.setTrailerId(trailerId);
        }

        // OTM接口地址
        otmLisaCarrier.setOtmApiUrl(otmApiUrl);

        // otm返回的请求id
        if (StringUtils.isNotEmpty(requestId)) {
            otmLisaCarrier.setRequestId(requestId);
        }
        // 保存日志
        blnRtn = this.insertOrUpdate(otmLisaCarrier);
        return blnRtn;
    }

    @Override
    public void updateCallbackResult(String returnMesssage) {
        Document document = null;
        LOGGER.info("回调返回信息", returnMesssage);
        if (StringUtils.isEmpty(returnMesssage)) {
            throw new BaseException("回调信息为空");
        }
        OtmLisaCarrier otmLisaCarrier = null;
        returnMesssage = returnMesssage.replaceAll(" xmlns:gtm=\"http://xmlns.oracle.com/apps/gtm/transmission/v6.4\" xmlns:otm=\"http://xmlns.oracle.com/apps/otm/transmission/v6.4\"", "").replaceAll("otm:", "");

        try {
            document = XmlUtil.parseByString(returnMesssage);
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage());
            throw new BaseException(ex.getMessage());
        }

        // 接口 id
        String requestIdPath = "/TransmissionReport/TransmissionNo";
        //得到根节点
        Element element = (Element) document.selectSingleNode(requestIdPath);
        //得到根节点的值
        String requestId = element.getText();

        try{
            EntityWrapper<OtmLisaCarrier> entityWrapper = new EntityWrapper<>();
            entityWrapper.eq("request_id",requestId);
            otmLisaCarrier = this.selectOne(entityWrapper);
            if(Objects.isNull(otmLisaCarrier)){
                otmLisaCarrier = new OtmLisaCarrier();
                otmLisaCarrier.setRequestId(requestId);
            }
        }
        catch (Exception ex){
            throw new BaseException(ex.getMessage());
        }

        if (StringUtils.isEmpty(requestId)) {
            throw new BaseException("返回的接口id为空");
        }

        // 处理结果
        String returnStatusPath = "/TransmissionReport/ReportStatus";
        //得到根节点
        Element elementReturnStatus = (Element) document.selectSingleNode(returnStatusPath);
        String returnStatus = elementReturnStatus.getText();
        otmLisaCarrier.setReturnMessage(returnStatus);
        Integer isSuccess = 0;
        if (!StringUtils.isEmpty(returnStatus) &&
                "PROCESSED".equals(returnStatus)) {
            isSuccess = 1;
        }
        otmLisaCarrier.setIsSuccess(isSuccess);

        // 处理时间
        String processTimePath = "/TransmissionReport/IntegrationLogMessage/DateTimeStamp/GLogDate";
        Element elementProcessTime = (Element) document.selectSingleNode(processTimePath);
        String processTime = elementProcessTime.getText();

        try {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
            Date otmDate = formatter.parse(processTime);
            DateTime dateTime = new DateTime(otmDate);
            dateTime = dateTime.plusHours(8);
            otmLisaCarrier.setGmtOmt(dateTime.toDate());
        } catch (Exception e) {
           throw new BaseException(e.getMessage());
        }

        // 更新请求结果
        this.insertOrUpdate(otmLisaCarrier);
    }

}
